package com.ericsson.enap.modules.backup.utils;

import com.ericsson.common.util.DateUtils;
import com.ericsson.common.util.LogFileName;
import com.ericsson.common.util.LoggerUtils;
import org.slf4j.Logger;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: 执行各种命令的工具类
 * @author: wangjingshi
 * @create: 2021-06-08 09:55
 */
public class ExecCmd {

    private static Logger log = LoggerUtils.Logger(LogFileName.ImsDataBackupJob);

    /**
     * 执行命令，取得backup目录下各个网元所需的最新的备份文件
     * @param cmd2
     * @param netName
     * @return
     */
    public static String GetBackupFilesCmd(String cmd2,String netName,int JobNo) {
        Process process = null;
        String result = "";
        String command[] = new String[3];
        command[0] = "sh";
        command[1] = "-c";
        command[2] = cmd2;
        log.info(JobNo+" "+netName+":"+cmd2);
        try {
            process = Runtime.getRuntime().exec(command);
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while((line = br.readLine())!=null){
                //适配CSCF、MTAS
                if(line.contains("BACKUP")){
                    result = line.substring(line.indexOf("BACKUP")).replaceAll("(\\x9B|\\x1B\\[|\u001B)[0-?]*[ -\\/]*[@-~]","");
                }
                //适配SBG
                if(line.contains("fortest.bak")){
                    result = "fortest.bak";
                }
            }
            br.close();
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(JobNo+" "+" ===== Exception in GetBackupFilesCmd =====" + e.getMessage() + " cmd:" + cmd2);
        } finally {
            process.destroy();
        }
        return result;
    }

    public static List<String> getSysLogCmd(String cmd2, String netName,Long netType,int JobNo) {
        Process process = null;
        String result = "";
        List<String> list = new ArrayList<>();
        String command[] = new String[3];
        command[0] = "sh";
        command[1] = "-c";
        command[2] = cmd2;
        log.info(JobNo+" "+netName+":"+cmd2);
        try {
            process = Runtime.getRuntime().exec(command);
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while((line = br.readLine())!=null){
                //SBG(101)的跟CSCF(103)和TAS(102)不一样
                if(netType==101){
                    if(line.contains("psbcc")&&line.contains("PL-")&&!line.contains("~")){
                        result = line.substring(line.indexOf("psbcc")-2).replaceAll("(\\x9B|\\x1B\\[|\u001B)[0-?]*[ -\\/]*[@-~]","");
                        //System.out.println("netName:"+netName+" ==== "+line);
                        list.add(result);
                    }
                    if(line.contains("psbcc")&&line.contains("SC-")&&!line.contains("~")&&!line.contains(">")){
                        result = line.substring(line.indexOf("psbcc")-2).replaceAll("(\\x9B|\\x1B\\[|\u001B)[0-?]*[ -\\/]*[@-~]","");
                        //System.out.println("netName:"+netName+" ==== "+line);
                        list.add(result);
                    }
                }else{
                    if(line.contains("PL-")&&!line.contains("nfs_logger")){
                    result = line.substring(line.indexOf("PL-")).replaceAll("(\\x9B|\\x1B\\[|\u001B)[0-?]*[ -\\/]*[@-~]","");
                    //System.out.println("netName:"+netName+" ==== "+line);
                    list.add(result);
                    }
                    if(line.contains("SC-")&&!line.contains("nfs_logger")&&!line.contains("~")&&!line.contains(">")){
                        result = line.substring(line.indexOf("SC-")).replaceAll("(\\x9B|\\x1B\\[|\u001B)[0-?]*[ -\\/]*[@-~]","");
                        //System.out.println("netName:"+netName+" ==== "+line);
                        list.add(result);
                    }
                }
            }
            br.close();
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(JobNo+" "+" ===== Exception in getSysLogCmd =====" + e.getMessage() + " cmd:" + cmd2);
        } finally {
            process.destroy();
        }
        return list;
    }

    public static String getLogDumpCmd(String cmd2, String netName, Long netType, int jobNo,String dateTime) {
        Process process = null;
        String result = "";
        String command[] = new String[3];
        command[0] = "sh";
        command[1] = "-c";
        command[2] = cmd2;
        log.info(jobNo+" "+netName+":"+cmd2);
        try {
            process = Runtime.getRuntime().exec(command);
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while((line = br.readLine())!=null){
                if(line.contains("logdump")){
                    line = line.replaceAll("(\\x9B|\\x1B\\[|\u001B)[0-?]*[ -\\/]*[@-~]","");
                    String res[] = line.split("\\s+");
                    if(res.length>8){
                        String fileTime = res[7];
                        String fileName = res[8];
                        String endTime = dateTime.substring(11);
                        String startTime = DateUtils.getBeforeNMinDateTime(endTime,30,"HH:mm:ss");
                        if(fileTime.compareTo(startTime)>=0&&fileTime.compareTo(endTime)<=0){
                            log.info(jobNo+" "+netName+" startTime "+startTime+" endTime "+endTime+" fileTime "+fileTime);
                            log.info(jobNo+" "+netName+" fileName "+fileName);
                            result = fileName;
                        }
                    }
                }
            }
            br.close();
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(jobNo+" "+" ===== Exception in getLogDumpCmd =====" + e.getMessage() + " cmd:" + cmd2);
        } finally {
            process.destroy();
        }
        return result;
    }

    /**
     * 普通执行命令方法
     * @param cmd2
     * @param netName
     */
    public static void executeCmd(String cmd2,String netName,int JobNo) {
        Process process = null;
        String command[] = new String[3];
        command[0] = "sh";
        command[1] = "-c";
        command[2] = cmd2;
        log.info(JobNo+" "+netName+":"+cmd2);
        try {
            process = Runtime.getRuntime().exec(command);
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while((line = br.readLine())!=null){
                //System.out.println("====line====:"+line);
            }
            br.close();
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(JobNo+" "+" ===== Exception in executeCmd =====" + e.getMessage() + " cmd:" + cmd2);
        } finally {
            process.destroy();
        }
    }

    /**
     * 执行压缩命令
     * @param cmd2
     * @param netName
     * @param localFile
     */
    public static void executeZipCmd(String cmd2, String netName, File localFile,int JobNo) {
        Process process = null;
        String command[] = new String[3];
        command[0] = "sh";
        command[1] = "-c";
        command[2] = cmd2;
        log.info(JobNo+" "+netName+":"+cmd2);
        try {
            process = Runtime.getRuntime().exec(command,null,localFile);
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while((line = br.readLine())!=null){
                //log.info(netName+" ===== "+line);
                //System.out.println(netName+" ===== "+line);
            }
            br.close();
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(JobNo+" "+" ===== Exception in executeZipCmd =====" + e.getMessage() + " cmd:" + cmd2);
        } finally {
            process.destroy();
        }
    }

    /**
     * kill 世凯脚本
     */
    public static void executeKillCmd(String cmd2,int JobNo) {
        Process process = null;
        String command[] = new String[3];
        command[0] = "sh";
        command[1] = "-c";
        command[2] = cmd2;
        log.info(JobNo+"==="+cmd2);
        try {
            process = Runtime.getRuntime().exec(command);
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while((line = br.readLine())!=null){
                log.info(JobNo+" "+" kill ===== "+line);
            }
            br.close();
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(JobNo+" "+" ===== Exception in executeKillCmd =====" + e.getMessage() + " cmd:" + cmd2);
        } finally {
            process.destroy();
        }
    }

    /**
     * ssh CG 执行命令取结果
     */
    public static List<String> executeCgCmd(String cmd2,int JobNo) {
        Process process = null;
        String command[] = new String[3];
        command[0] = "sh";
        command[1] = "-c";
        command[2] = cmd2;
        log.info(JobNo+"==="+cmd2);
        List<String> list = new ArrayList<>();
        try {
            process = Runtime.getRuntime().exec(command);
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while((line = br.readLine())!=null){
                list.add(line);
            }
            br.close();
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(JobNo+" "+" ===== Exception in executeCgCmd =====" + e.getMessage() + " cmd:" + cmd2);
        } finally {
            process.destroy();
        }
        return list;
    }


    public static List<String> getPsbccCmd(String cmd2,String netName,int JobNo) {
        Process process = null;
        String result = "";
        List<String> list = new ArrayList<>();
        String command[] = new String[3];
        command[0] = "sh";
        command[1] = "-c";
        command[2] = cmd2;
        log.info(JobNo+" "+netName+":"+cmd2);
        try {
            process = Runtime.getRuntime().exec(command);
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while((line = br.readLine())!=null){
                if(line.contains("psbcc")&&line.contains("PL-")&&!line.contains("~")){
                    result = line.substring(line.indexOf("psbcc")-2).replaceAll("(\\x9B|\\x1B\\[|\u001B)[0-?]*[ -\\/]*[@-~]","");
                    //System.out.println("netName:"+netName+" ==== "+line);
                    list.add(result);
                }
            }
            br.close();
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(JobNo+" "+" ===== Exception in getSysLogCmd =====" + e.getMessage() + " cmd:" + cmd2);
        } finally {
            process.destroy();
        }
        return list;
    }

    public static void main(String[] args) {
        String a = "-rw-rw---- 1 lem-cdcls lem-cdcls-users 2792880544 Jun 16 13:16 logdump-20210616-130000.013.tgz";
        System.out.println(a.split("\\s++")[8]);

        String d = DateUtils.getBeforeNMinDateTime("15:59:00",30,"HH:mm:ss");
        System.out.println(d);

    }
}
